package org.springblade.protocol;

import cn.hutool.core.thread.ThreadUtil;
import org.springblade.cache.DeviceManagerCache;
import org.springblade.common.constant.ProtocolConstant;
import org.springblade.common.tool.ThreadPoolUtils;
import org.springblade.protocol.tcp.client.SocketClient;
import org.springblade.protocol.tcp.server.SocketServer;
import org.springblade.vo.ProductVO;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * 初始化链接
 * @author lijiamin
 */
@Component
public class InitConnect {

	@PostConstruct
	private void starter() {
		CompletableFuture.runAsync(() -> {
			ThreadUtil.sleep(6, TimeUnit.SECONDS);

			// todo 每次重启先更新数据库状态为全部离线



			List<ProductVO> products = DeviceManagerCache.getDeviceManagerClient().initConnect();
			for (ProductVO product : products) {
				switch (product.getProtocol()) {
					case ProtocolConstant.TCP_SERVER:
						SocketClient.connectServer(product.getIpAddr(), product.getPort());
						break;
					// todo
				}
			}
			SocketServer.initServer();




			// todo 还有连接心跳检查

		}, ThreadPoolUtils.getThreadPool());
	}


}
